using GomokuGame.AI;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace GomokuGame
{
    /// <summary>
    /// 设置窗体
    /// </summary>
    public partial class SettingsForm : Form
    {
        private GameSettings settings;
        private bool settingsChanged = false;

        public SettingsForm()
        {
            InitializeComponent();
            settings = GameSettings.Instance;
            LoadSettings();
        }

        /// <summary>
        /// 加载设置到界面
        /// </summary>
        private void LoadSettings()
        {
            // 游戏设置
            numericBoardSize.Value = settings.BoardSize;
            checkBoxSoundEnabled.Checked = settings.SoundEnabled;
            checkBoxBackgroundMusic.Checked = settings.BackgroundMusicEnabled;
            trackBarSoundVolume.Value = settings.SoundVolume;
            trackBarMusicVolume.Value = settings.MusicVolume;
            comboBoxTheme.SelectedItem = settings.Theme;
            numericMaxUndo.Value = settings.MaxUndoCount;
            checkBoxAutoSave.Checked = settings.AutoSaveGameRecord;
            numericKeepRecords.Value = settings.KeepGameRecordsDays;

            // AI设置
            comboBoxDefaultAI.SelectedItem = settings.DefaultAIDifficulty.ToString();
            numericAITimeLimit.Value = settings.AITimeLimit / 1000; // 转换为秒
            numericAISearchDepth.Value = settings.AISearchDepth;
            checkBoxShowAIProgress.Checked = settings.ShowAIThinkingProgress;
            trackBarAttackWeight.Value = (int)(settings.AIAttackWeight * 10);
            trackBarDefenseWeight.Value = (int)(settings.AIDefenseWeight * 10);
            trackBarPositionWeight.Value = (int)(settings.AIPositionWeight * 10);

            // 界面设置
            numericWindowWidth.Value = settings.WindowWidth;
            numericWindowHeight.Value = settings.WindowHeight;
            checkBoxWindowMaximized.Checked = settings.WindowMaximized;
            panelBoardColor.BackColor = settings.BoardBackgroundColor;
            panelLineColor.BackColor = settings.BoardLineColor;
            panelBlackPiece.BackColor = settings.BlackPieceColor;
            panelWhitePiece.BackColor = settings.WhitePieceColor;
            panelBorderColor.BackColor = settings.PieceBorderColor;
            panelLastMoveColor.BackColor = settings.LastMoveColor;
            comboBoxPieceStyle.SelectedItem = settings.PieceStyle;
            numericFontSize.Value = (decimal)settings.FontSize;
            comboBoxFontName.SelectedItem = settings.FontName;
            checkBoxShowGridLines.Checked = settings.ShowGridLines;
            checkBoxShowCoordinates.Checked = settings.ShowCoordinates;
            checkBoxShowLastMove.Checked = settings.ShowLastMove;

            UpdateLabels();
        }

        /// <summary>
        /// 更新标签显示
        /// </summary>
        private void UpdateLabels()
        {
            labelSoundVolume.Text = $"音效音量: {trackBarSoundVolume.Value}%";
            labelMusicVolume.Text = $"音乐音量: {trackBarMusicVolume.Value}%";
            labelAttackWeight.Text = $"攻击权重: {trackBarAttackWeight.Value / 10.0:F1}";
            labelDefenseWeight.Text = $"防守权重: {trackBarDefenseWeight.Value / 10.0:F1}";
            labelPositionWeight.Text = $"位置权重: {trackBarPositionWeight.Value / 10.0:F1}";
        }

        /// <summary>
        /// 保存设置
        /// </summary>
        private void SaveSettings()
        {
            try
            {
                // 游戏设置
                settings.BoardSize = (int)numericBoardSize.Value;
                settings.SoundEnabled = checkBoxSoundEnabled.Checked;
                settings.BackgroundMusicEnabled = checkBoxBackgroundMusic.Checked;
                settings.SoundVolume = trackBarSoundVolume.Value;
                settings.MusicVolume = trackBarMusicVolume.Value;
                settings.Theme = comboBoxTheme.SelectedItem?.ToString() ?? "默认";
                settings.MaxUndoCount = (int)numericMaxUndo.Value;
                settings.AutoSaveGameRecord = checkBoxAutoSave.Checked;
                settings.KeepGameRecordsDays = (int)numericKeepRecords.Value;

                // AI设置
                if (comboBoxDefaultAI.SelectedItem != null)
                {
                    if (Enum.TryParse<AIDifficulty>(comboBoxDefaultAI.SelectedItem.ToString(), out var difficulty))
                    {
                        settings.DefaultAIDifficulty = difficulty;
                    }
                }
                settings.AITimeLimit = (int)numericAITimeLimit.Value * 1000; // 转换为毫秒
                settings.AISearchDepth = (int)numericAISearchDepth.Value;
                settings.ShowAIThinkingProgress = checkBoxShowAIProgress.Checked;
                settings.AIAttackWeight = trackBarAttackWeight.Value / 10.0;
                settings.AIDefenseWeight = trackBarDefenseWeight.Value / 10.0;
                settings.AIPositionWeight = trackBarPositionWeight.Value / 10.0;

                // 界面设置
                settings.WindowWidth = (int)numericWindowWidth.Value;
                settings.WindowHeight = (int)numericWindowHeight.Value;
                settings.WindowMaximized = checkBoxWindowMaximized.Checked;
                settings.BoardBackgroundColor = panelBoardColor.BackColor;
                settings.BoardLineColor = panelLineColor.BackColor;
                settings.BlackPieceColor = panelBlackPiece.BackColor;
                settings.WhitePieceColor = panelWhitePiece.BackColor;
                settings.PieceBorderColor = panelBorderColor.BackColor;
                settings.LastMoveColor = panelLastMoveColor.BackColor;
                settings.PieceStyle = comboBoxPieceStyle.SelectedItem?.ToString() ?? "圆形";
                settings.FontSize = (float)numericFontSize.Value;
                settings.FontName = comboBoxFontName.SelectedItem?.ToString() ?? "微软雅黑";
                settings.ShowGridLines = checkBoxShowGridLines.Checked;
                settings.ShowCoordinates = checkBoxShowCoordinates.Checked;
                settings.ShowLastMove = checkBoxShowLastMove.Checked;

                // 保存到文件
                settings.Save();
                settingsChanged = false;
                MessageBox.Show("设置已保存成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存设置失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 重置为默认设置
        /// </summary>
        public void ResetToDefault()
        {
            if (MessageBox.Show("确定要重置所有设置为默认值吗？", "确认重置", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                settings.ResetToDefault();
                LoadSettings();
                settingsChanged = true;
            }
        }

        #region 事件处理

        public void buttonOK_Click(object sender, EventArgs e)
        {
            SaveSettings();
            DialogResult = DialogResult.OK;
            Close();
        }

        public void buttonCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        public void buttonApply_Click(object sender, EventArgs e)
        {
            SaveSettings();
        }

        public void buttonReset_Click(object sender, EventArgs e)
        {
            ResetToDefault();
        }

        public void trackBarSoundVolume_ValueChanged(object sender, EventArgs e)
        {
            labelSoundVolume.Text = $"音效音量: {trackBarSoundVolume.Value}%";
            settingsChanged = true;
        }

        public void trackBarMusicVolume_ValueChanged(object sender, EventArgs e)
        {
            labelMusicVolume.Text = $"音乐音量: {trackBarMusicVolume.Value}%";
            settingsChanged = true;
        }

        public void trackBarAttackWeight_ValueChanged(object sender, EventArgs e)
        {
            labelAttackWeight.Text = $"攻击权重: {trackBarAttackWeight.Value / 10.0:F1}";
            settingsChanged = true;
        }

        public void trackBarDefenseWeight_ValueChanged(object sender, EventArgs e)
        {
            labelDefenseWeight.Text = $"防守权重: {trackBarDefenseWeight.Value / 10.0:F1}";
            settingsChanged = true;
        }

        public void trackBarPositionWeight_ValueChanged(object sender, EventArgs e)
        {
            labelPositionWeight.Text = $"位置权重: {trackBarPositionWeight.Value / 10.0:F1}";
            settingsChanged = true;
        }

        public void buttonBoardColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelBoardColor.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelBoardColor.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void buttonLineColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelLineColor.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelLineColor.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void buttonBlackPieceColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelBlackPiece.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelBlackPiece.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void buttonWhitePieceColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelWhitePiece.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelWhitePiece.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void buttonBorderColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelBorderColor.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelBorderColor.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void buttonLastMoveColor_Click(object sender, EventArgs e)
        {
            using (var colorDialog = new ColorDialog())
            {
                colorDialog.Color = panelLastMoveColor.BackColor;
                if (colorDialog.ShowDialog() == DialogResult.OK)
                {
                    panelLastMoveColor.BackColor = colorDialog.Color;
                    settingsChanged = true;
                }
            }
        }

        public void SettingsForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (settingsChanged)
            {
                var result = MessageBox.Show("设置已更改，是否保存？", "保存设置", 
                    MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                
                switch (result)
                {
                    case DialogResult.Yes:
                        SaveSettings();
                        break;
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;
                }
            }
        }

        #endregion
    }
} 